package com.daisuxia.ts.service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.daisuxia.back.utils.SysCacheUtils;
import com.daisuxia.back.utils.WebClient;
import com.daisuxia.constant.Constant;
import com.daisuxia.jms.JMSsendMessageUtil;
import com.daisuxia.ts.dao.ITsOrdersDao;
import com.daisuxia.ts.pojo.SyBody;
import com.daisuxia.ts.pojo.SyRevice;
import com.daisuxia.ts.pojo.SyUserVo;
import com.daisuxia.ts.pojo.TsOrders;
import com.daisuxia.ts.utils.SyUtils;
import com.daisuxia.web.dao.IPaginationDao;
import com.daisuxia.web.pojo.BackConfigParams;
import com.daisuxia.web.pojo.BorrowOrder;
import com.daisuxia.web.pojo.User;
import com.daisuxia.web.util.DateUtil;
import com.daisuxia.web.util.JSONUtil;
import com.daisuxia.web.util.PageConfig;
import com.daisuxia.web.util.ThreadPool3;
import com.daisuxia.web.util.encrypt.MD5coding;

@Service
public class TsOrdersService implements ITsOrdersService {
	Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private ITsOrdersDao tsOrdersDao;
	@Autowired
	private IPaginationDao paginationDao;

	@Override
	public void sendSyReg() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date now = new Date();
		String begin = sdf.format(DateUtil.addDay(now, -2));
		String end = sdf.format(now);
		Map<String, String> map = SysCacheUtils.getConfigMap(BackConfigParams.SY_TS);
		final HashMap<String, Object> params = new HashMap<String, Object>();
		params.put("begin", begin);
		params.put("end", end);
		params.put("userFrom", map.get("SY_TS_ID"));
		PageConfig<SyUserVo> pm = new PageConfig<SyUserVo>();
		pm.setTotalPageNum(1);
		params.put(Constant.NAME_SPACE, "TsOrders");
		params.put(Constant.PAGE_SIZE, "100");
		final String channle = map.get("SY_TS_CHANNEL");
		final String url = map.get("SY_TS_URL_REG");
		final String yz = map.get("SY_TS_YZ");
		for (int i = 1; i <= pm.getTotalPageNum(); i++) {
			try {
				params.put(Constant.CURRENT_PAGE, i);
				pm = paginationDao.findPage("findReg", "findRegCount", params, "ts");
				logger.info("sendSyReg query db pm=" + pm + ",params=" + params);
				if (pm.getItems() != null && pm.getItems().size() > 0) {
					final String data = JSONUtil.beanListToJson(pm.getItems());
					ThreadPool3.getInstance().run(new Runnable() {
						@Override
						public void run() {
							HashMap<String, String> map1 = new HashMap<String, String>();
							map1.put("jsonData", data);
							map1.put("sign", MD5coding.getInstance().MD5(data + yz));
							map1.put("channel", channle);
							logger.info("sendSyReg send map1=" + map1);
							String result = WebClient.getInstance().doPost(url, map1);
							logger.info("sendSyReg map1=" + map1 + ",return " + result);
						}
					});
				}
			} catch (Exception e) {
				logger.error("sendSyReg error params=" + params, e);
			}

		}
	}

	@Override
	public void updateSy(HashMap<String, Object> params) {
		boolean suc = false;
		Date now = null;
		Integer userId = Integer.valueOf(params.get("userId") + "");
		Integer status = Integer.valueOf(params.get("status") + "");
		Object orderNo2 = params.get("orderNo");
		Map<String, String> map = SysCacheUtils.getConfigMap(BackConfigParams.SY_TS);
		Integer userFrom = Integer.valueOf(map.get("SY_TS_ID"));
		String json = null;
		String result = null;
		String sendLog = "未知异常";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		User user = tsOrdersDao.findUser(new TsOrders(userId, userFrom));
		String orderNo = null;
		try {
			if (user != null) {
				if (orderNo2 == null) {
					BorrowOrder borrowOrder = tsOrdersDao.findBorrowById(Integer.valueOf(params.get("assetId") + ""));
					orderNo = borrowOrder.getOutTradeNo();
				} else {
					orderNo = orderNo2 + "";
				}
				HashMap<String, Object> map2 = tsOrdersDao.findSy(orderNo);
				String date = sdf.format(sdf.parse(map2.get("order_time") + ""));
				SyBody syBody = new SyBody(user.getTgFlag(), orderNo, Integer.valueOf(map2.get("into_money") + "") / 100 + "", "1", date + "",
						Integer.valueOf(map2.get("money_amount") + "") / 100 + "", SyUtils.changeStatus(status));
				json = JSONUtil.beanToJson(syBody);
				logger.info("send sy params=" + params + ",json=" + json);
				now = new Date();
				HashMap<String, String> map1 = new HashMap<String, String>();
				String data = JSONUtil.beanToJson(syBody);
				map1.put("jsonData", data);
				map1.put("sign", MD5coding.getInstance().MD5(data + map.get("SY_TS_YZ")));
				map1.put("channel", map.get("SY_TS_CHANNEL"));
				result = WebClient.getInstance().doPost(map.get("SY_TS_URL"), map1);
				logger.info("recive sy params=" + params + ",json=" + json + ",return " + result);
				if (StringUtils.isNotBlank(result)) {
					try {
						SyRevice syRevice = JSONUtil.jsonToBean(result, SyRevice.class);
						if (syRevice.isSuccessed()) {
							suc = true;
						}
					} catch (Exception e) {
						logger.error("sy first result error ", e);
					}
				}
			} else {
				suc = true;
			}

		} catch (Exception e) {
			logger.error("updateSy error params=" + params, e);
		} finally {
			if (!suc) {
				tsOrdersDao.updateStatus(orderNo);
				sendLog = sdf.format(now) + "首次发送失败,返回结果" + result + ";";
				Date nextTime = DateUtil.addMinute(now, Integer.valueOf(map.get("SY_TS_INTERVAL")));
				tsOrdersDao.insert(new TsOrders(userId, user.getTgFlag(), userFrom, orderNo, json, sendLog, 1, nextTime));
			}
		}
	}

	@Override
	public void updateRetry() {
		final Map<String, String> map = SysCacheUtils.getConfigMap(BackConfigParams.SY_TS);
		Integer userFrom = Integer.valueOf(map.get("SY_TS_ID"));
		final Integer limit = Integer.valueOf(map.get("SY_TS_LIMIT"));
		List<TsOrders> list = tsOrdersDao.findList(userFrom);
		if (list != null && list.size() > 0) {
			final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			for (final TsOrders tsOrders : list) {
				try {
					ThreadPool3.getInstance().run(new Runnable() {
						@Override
						public void run() {
							try {
								Integer num = tsOrders.getSendNum();
								int status = tsOrders.getStatus();
								String sendLog = tsOrders.getSendLog();
								Date nextTime = tsOrders.getNextTime();
								if (num < limit) {
									boolean suc = false;
									String orderNo = tsOrders.getOrderNo();
									String json = tsOrders.getParams();
									HashMap<String, Object> map2 = tsOrdersDao.findSy(orderNo);
									Date now = new Date();
									String date = sdf.format(sdf.parse(map2.get("order_time") + ""));
									SyBody syBody = new SyBody(tsOrders.getTgFlag(), orderNo,
											Integer.valueOf(map2.get("into_money") + "") / 100 + "", "1", date + "", Integer.valueOf(map2
													.get("money_amount")
													+ "")
													/ 100 + "", SyUtils.changeStatus(Integer.valueOf(map2.get("status") + "")));
									json = JSONUtil.beanToJson(syBody);
									logger.info("send sy json=" + json);
									HashMap<String, String> map1 = new HashMap<String, String>();
									String data = JSONUtil.beanToJson(syBody);
									map1.put("jsonData", data);
									map1.put("sign", MD5coding.getInstance().MD5(data + map.get("SY_TS_YZ")));
									map1.put("channel", map.get("SY_TS_CHANNEL"));
									String result = WebClient.getInstance().doPost(map.get("SY_TS_URL"), map1);
									logger.info("resend recive sy json=" + json + ",return " + result);
									if (StringUtils.isNotBlank(result)) {
										SyRevice syRevice = JSONUtil.jsonToBean(result, SyRevice.class);
										if (syRevice.isSuccessed()) {
											suc = true;
										}
									}
									num += 1;
									if (num >= limit) {
										if (suc) {
											status = 2;
										} else {
											status = 3;
										}
									}
									if (!suc && status == 1) {
										nextTime = DateUtil.addMinute(now, Integer.valueOf(map.get("SY_TS_INTERVAL")));
									}
									sendLog += sdf.format(now) + "发送,返回结果" + result + ";";
								} else {
									status = 3;
								}
								tsOrders.setSendLog(sendLog);
								tsOrders.setSendNum(num);
								tsOrders.setNextTime(nextTime);
								tsOrders.setStatus(status);
								tsOrdersDao.update(tsOrders);
							} catch (Exception e) {
								logger.error("", e);
							}
						}
					});
				} catch (Exception e) {
					logger.error("updateRetry error tsOrders=" + tsOrders.toString(), e);
				}
			}
		}
	}


	@Override
	public void sendBorrowStatus(Integer borrowId) {
		
		BorrowOrder borrowOrder = tsOrdersDao.findBorrowById(borrowId);
		if (borrowOrder != null) { 
		String tg = tsOrdersDao.findUserTg(borrowOrder.getUserId());
		if (StringUtils.isNotBlank(tg) && !"0".equals(tg)) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("borrowId", borrowId+"QQ"+tg);
		JMSsendMessageUtil.getInstance().sendMes(map);
			}
		}
	}
	
	@Override
	public void sendBorrowStatusByBatch(List<BorrowOrder> jmsPojoList){
		  for(BorrowOrder  borrowOrder : jmsPojoList){
			String tg = tsOrdersDao.findUserTg(borrowOrder.getUserId());
			if (StringUtils.isNotBlank(tg) && !"0".equals(tg)) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("borrowId", borrowOrder.getId()+"QQ"+tg);
				JMSsendMessageUtil.getInstance().sendMes(map); 

				}
			 }
					
		}
		
	
}
